//
//  XMEmoticonToolbar.swift
//  XMWeimo
//
//  Created by ios001 on 16/7/29.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let tagNum = 2000

// 按钮枚举
enum XMEmoticonToolbarType: Int {
    // 默认
    case Default = 0
    // Emoji
    case Emoji = 1
    // 浪小花
    case Lxh = 2
}

class XMEmoticonToolbar: UIStackView {
    // 定义一个闭包
    var closure:((type:XMEmoticonToolbarType)->())?
    // 当前选中的按钮
    var currentButton: UIButton?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 供外界调用方法
    func setupCurrentButton(tag: Int) {
        let button = viewWithTag(tag + tagNum) as! UIButton
        setupCurrentButtons(button)
    }
    
    // 设置当前选中的button
    func setupCurrentButtons(button: UIButton) {
        // 如果点击的button为当前记录的button 直接返回
        if button == currentButton {
            return
        }
        /*
        01 把当前的button 状态该我false
        02 把点击的button 状态改为true
        03 给当前的button赋值
        */
        currentButton?.selected = false
        button.selected = true
        currentButton = button
    }
    // MARK: - 监听方法
    func buttonClick(button: UIButton) {
        setupCurrentButtons(button)
        // 执行闭包
        closure?(type: XMEmoticonToolbarType(rawValue: button.tag - tagNum)!)
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        // 设置排列方向
        axis = .Horizontal
        // 填充方式
        distribution = .FillEqually
        addClildButton("left", title: "默认",type: .Default)
        addClildButton("mid", title: "Emoji",type: .Emoji)
        addClildButton("right", title: "浪小花",type: .Lxh)
    }
    
    // MARK: - 创建button
    func addClildButton(imgName: String, title: String, type: XMEmoticonToolbarType){
        let button = UIButton()
        // 默认情况下,默认按钮被选中
        if type == .Default {
//            button.selected = true
//            currentButton = button
            setupCurrentButtons(button)
        }
        button.tag = type.rawValue + tagNum
        // 添加点击事件
        button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setTitle(title, forState: UIControlState.Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Selected)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imgName)_normal"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imgName)_selected"), forState: UIControlState.Selected)
//        addSubview(button)
        addArrangedSubview(button)
    }
}
